//
//  CardFormViewController.m
//  MoneyBook
//
//  Created by MyoungHo Kim on 11. 7. 8..
//  Copyright 2011 Daum. All rights reserved.
//

#import "CardFormViewController.h"

@implementation CardFormViewController
@synthesize bankId = _bankId;
@synthesize cardId = _cardId;
//@synthesize startDay = _startDay;
//@synthesize endDay = _endDay;
//@synthesize payDay = _payDay;

@synthesize cardTitle = _cardTitle;
@synthesize defaultSwitch = _defaultSwitch;
@synthesize startDayTextField = _startDayTextField;
@synthesize endDayTextField = _endDayTextField;
@synthesize payDayTextField = _payDayTextField;
@synthesize bankBtn = _bankBtn;

@synthesize numberPadDoneImageHighlighted = _numberPadDoneImageHighlighted;
@synthesize numberPadDoneImageNormal = _numberPadDoneImageNormal;
@synthesize numberPadDoneButton = _numberPadDoneButton;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave
                                                                                  target:self
                                                                                  action:@selector(saveAction)];
        [self.navigationItem setRightBarButtonItem:rightBtn];
        [rightBtn release];
        self.numberPadDoneImageNormal = [UIImage imageNamed:@"doneup.png"];
        self.numberPadDoneImageHighlighted = [UIImage imageNamed:@"donedown.png"];
        
    }
    return self;
}

- (void)dealloc{
    [_cardId release];
    [_bankId release];
//    [_startDay release];
//    [_endDay release];
//    [_payDay release];

    [_cardTitle release];
    [_defaultSwitch release];
    [_bankBtn release];
    [_startDayTextField release];
    [_endDayTextField release];
    [_payDayTextField release];

    [_numberPadDoneImageNormal release];
    [_numberPadDoneImageHighlighted release];
    [_numberPadDoneButton release];

    [super dealloc];
}

- (void)didReceiveMemoryWarning{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
- (void)viewDidLoad{
    [super viewDidLoad];
    _cardTitle.borderStyle = UITextBorderStyleRoundedRect;
    _cardTitle.textColor = [UIColor blackColor];
    _cardTitle.font = [UIFont systemFontOfSize:15.0];
    _cardTitle.backgroundColor = [UIColor whiteColor];
    _cardTitle.autocorrectionType = UITextAutocorrectionTypeNo;
    _cardTitle.keyboardType = UIKeyboardTypeDefault;
    _cardTitle.returnKeyType = UIReturnKeyDone;
    _cardTitle.clearButtonMode = UITextFieldViewModeWhileEditing;
    _cardTitle.placeholder = @"이름을 입력 해 주세요.";
    
    _startDayTextField.placeholder = @"카드 사용 시작 일을 입력 해 주세요.";
    _startDayTextField.keyboardType = UIKeyboardTypeNumberPad;
    _startDayTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    _endDayTextField.placeholder = @"카드 사용 마지막 일을 입력 해 주세요.";
    _endDayTextField.keyboardType = UIKeyboardTypeNumberPad;
    _endDayTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    _payDayTextField.placeholder = @"카드 사용 결제일을 입력 해 주세요.";
    _payDayTextField.keyboardType = UIKeyboardTypeNumberPad;    
    _payDayTextField.clearButtonMode = UITextFieldViewModeWhileEditing;

}
- (void)viewDidUnload{
    NSLog(@"viewDidUnLoad");
    [self setCardId:nil];
    [self setBankId:nil];
//    [self setStartDay:nil];
//    [self setEndDay:nil];
//    [self setPayDay:nil];

    [self setCardTitle:nil];
    [self setBankBtn:nil];
    [self setStartDayTextField:nil];
    [self setEndDayTextField:nil];
    [self setPayDayTextField:nil];
    [self setDefaultSwitch:nil];
    
    [self setNumberPadDoneImageNormal:nil];
    [self setNumberPadDoneImageHighlighted:nil];
    [self setNumberPadDoneButton:nil];

    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated{
	[super viewWillAppear:animated];
    // Add listener for keyboard display events
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(keyboardDidShow:) 
                                                     name:UIKeyboardDidShowNotification 
                                                   object:nil];     
    } else {
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(keyboardWillShow:) 
                                                     name:UIKeyboardWillShowNotification 
                                                   object:nil];
    }
    
    // Add listener for all text fields starting to be edited
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(textFieldDidBeginEditing:)
                                                 name:UITextFieldTextDidBeginEditingNotification 
                                               object:nil];
}
- (void)viewWillDisappear:(BOOL)animated{
    NSLog(@"viewWillDisappear");    
    [super viewWillDisappear:YES];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
        [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                        name:UIKeyboardDidShowNotification 
                                                      object:nil];      
    } else {
        [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                        name:UIKeyboardWillShowNotification 
                                                      object:nil];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UITextFieldTextDidBeginEditingNotification 
                                                  object:nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark -
#pragma mark UIButtonDelegate
/////////////////////////////////////////////////////////////////////////////////////////////////
- (IBAction)btnAction:(id)sender{
    PayPickerViewController* viewController = [[[PayPickerViewController alloc] initWithNibName:@"PayPickerView" bundle:nil] autorelease];
//    viewController.targetBtn = _bankBtn;
    viewController.payType = PAY_BANK;
    [viewController setPickerResultDelegate:self];
    [[self navigationController] pushViewController:viewController animated:YES];
}
- (void)doneButton{
    
}
#pragma mark -
#pragma mark UIBarButtonCardDelegate
/////////////////////////////////////////////////////////////////////////////////////////////////
- (void)saveAction{
    NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterDecimalStyle];

    SQLHandler *sql = [SQLHandler sharedInstance];
    if(_isCreateMode){
        [sql createCardIdWithTitle:[_cardTitle text]
                            bankId:_bankId
                          startDay:[f numberFromString:[_startDayTextField text]]
                            endDay:[f numberFromString:[_endDayTextField text]]
                            payDay:[f numberFromString:[_payDayTextField text]]
                           isCheck:[_defaultSwitch isOn]];
    }else{
        //        NSLog(@"saveActoin:  %@",  [_cardTitle text]);
        [sql updateCardId:_cardId
                    title:[_cardTitle text]
                   bankId:_bankId
                 startDay:[f numberFromString:[_startDayTextField text]]
                   endDay:[f numberFromString:[_endDayTextField text]]
                   payDay:[f numberFromString:[_payDayTextField text]]
                  isCheck:[_defaultSwitch isOn]];
    }
    [f release];
    [[self navigationController] popViewControllerAnimated:YES];
}
#pragma mark -
#pragma mark PickerResultDelegate
/////////////////////////////////////////////////////////////////////////////////////////////////
- (void)applyResultSet:(id)sender resultDic:(NSDictionary *)resultDic{
//    NSLog(@"result:%@", resultDic);
    self.bankId = [resultDic objectForKey:@"payId"];
    [self.bankBtn setTitle:[resultDic objectForKey:@"payName"] forState:UIControlStateNormal];
}
#pragma mark -
#pragma mark user methods
/////////////////////////////////////////////////////////////////////////////////////////////////
- (void)loadCard:(NSNumber*)cardId{
    _isCreateMode = NO;
    NSDictionary *dic = [[SQLHandler sharedInstance] findCardById:cardId];
    //    NSLog(@"dic:%@",dic);
    self.cardId = cardId;
    self.bankId = [dic objectForKey:@"bank_id"];
    
    [self.cardTitle setText:[dic objectForKey:@"title"]];
    [self.startDayTextField setText:[NSString stringWithFormat:@"%d", [[dic objectForKey:@"start_day"] intValue]]];
    [self.endDayTextField setText:[NSString stringWithFormat:@"%d", [[dic objectForKey:@"end_day"] intValue]]];
    [self.payDayTextField setText:[NSString stringWithFormat:@"%d", [[dic objectForKey:@"pay_day"] intValue]]];    

    NSDictionary *bankDic = [[SQLHandler sharedInstance] findBankById:_bankId];
    NSLog(@"bankDic:%@", bankDic);
    [self.bankBtn setTitle:[bankDic objectForKey:@"title"] forState:UIControlStateNormal];
    
    if([[dic objectForKey:@"is_check"] isEqualToString:@"y"]){
        [_defaultSwitch setOn:YES];
    }else{
        [_defaultSwitch setOn:NO];
    }
}
/////////////////////////////////////////////////////////////////////////////////////////////////
-(void)createMode{
    _isCreateMode = YES;    
}
/////////////////////////////////////////////////////////////////////////////////////////////////


- (UIView *)findFirstResponderUnder:(UIView *)root {
    if (root.isFirstResponder)
        return root;    
    for (UIView *subView in root.subviews) {
        UIView *firstResponder = [self findFirstResponderUnder:subView];        
        if (firstResponder != nil)
            return firstResponder;
    }
    return nil;
}


- (UITextField *)findFirstResponderTextField {
    UIResponder *firstResponder = [self findFirstResponderUnder:[self.view window]];
    if (![firstResponder isKindOfClass:[UITextField class]])
        return nil;
    return (UITextField *)firstResponder;
}

- (void)updateKeyboardButtonFor:(UITextField *)textField {
    [self.numberPadDoneButton removeFromSuperview];
    self.numberPadDoneButton = nil;
    
    if (textField.keyboardType != UIKeyboardTypeNumberPad)
        return;
    
    if ([[[UIApplication sharedApplication] windows] count] < 2)
        return;
    UIWindow *keyboardWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    
    self.numberPadDoneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.numberPadDoneButton.frame = CGRectMake(0, 163, 106, 53);
    self.numberPadDoneButton.adjustsImageWhenHighlighted = FALSE;
    [self.numberPadDoneButton setImage:self.numberPadDoneImageNormal forState:UIControlStateNormal];
    [self.numberPadDoneButton setImage:self.numberPadDoneImageHighlighted forState:UIControlStateHighlighted];
    [self.numberPadDoneButton addTarget:self action:@selector(numberPadDoneButton:) forControlEvents:UIControlEventTouchUpInside];
    
    NSString *keyboardPrefix = [[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2 ? @"<UIPeripheralHost" : @"<UIKeyboard";
    for (UIView *subView in keyboardWindow.subviews) {
        if ([[subView description] hasPrefix:keyboardPrefix]) {
            [subView addSubview:self.numberPadDoneButton];
            [self.numberPadDoneButton addTarget:self action:@selector(numberPadDoneButton:) forControlEvents:UIControlEventTouchUpInside];
            break;
        }
    }
}

- (void)textFieldDidBeginEditing:(NSNotification *)note {
    [self updateKeyboardButtonFor:[note object]];
}

- (void)keyboardWillShow:(NSNotification *)note {
    [self updateKeyboardButtonFor:[self findFirstResponderTextField]];
}

- (void)keyboardDidShow:(NSNotification *)note {
    [self updateKeyboardButtonFor:[self findFirstResponderTextField]];
}

- (IBAction)numberPadDoneButton:(id)sender {
    UITextField *textField = [self findFirstResponderTextField];
    [textField resignFirstResponder];
}
@end
